package com.yanqu.road.dao.impl.player;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.marriage.MarriageRecord;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MarriageRecordDaoImpl extends TempDataObjectDao<MarriageRecord> {

    public LinkedList<MarriageRecord> getMarriageRecordList(long userId, int maxCount) {
        ResultSet rs = null;
        CallableStatement call = null;
        LinkedList<MarriageRecord> dataList = new LinkedList<>();
        String sql = "select * from t_u_marriage_record where userId=? order by marriageTime desc limit ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            call.setInt(2, maxCount);
            rs = call.executeQuery();
            while (rs.next()) {
                MarriageRecord data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    @Override
    protected boolean addData(MarriageRecord data) {
        PreparedStatement call = null;
        String sql = "insert into t_u_marriage_record(userId,userNickName,childUid,childTalent,childOccupation,childName,childSex,childHeadIcon,"
                + "childAdultTime,publishTime,appointUserId,reward,marriageTime,partnerUserId,partnerNickName,partnerChildUid,partnerChildTalent,"
                + "partnerChildOccupation,partnerChildName,partnerChildSex,partnerChildHeadIcon,partnerReward,childOccupationId,childEarnSpeed,"
                + "partnerChildOccupationId,partnerChildEarnSpeed,totalChildEarnSpeed,motherId,partnerMotherId,isTwins,isPartnerTwins,serverId," +
                "partnerServerId,canHoneyMoon) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getUserId());
            call.setString(i++, data.getUserNickName());
            call.setString(i++, data.getChildUid());
            call.setInt(i++, data.getChildTalent());
            call.setInt(i++, data.getChildOccupation());
            call.setString(i++, data.getChildName());
            call.setInt(i++, data.getChildSex());
            call.setInt(i++, data.getChildHeadIcon());
            call.setLong(i++, data.getChildAdultTime());
            call.setLong(i++, data.getPublishTime());
            call.setLong(i++, data.getAppointUserId());
            String reward = PropertyHelper.parsePropertyToString(data.getReward());
            if(null == reward){
                reward = "";
            }
            call.setString(i++, reward);
            call.setLong(i++, data.getMarriageTime());
            call.setLong(i++, data.getPartnerUserId());
            call.setString(i++, data.getPartnerNickName());
            call.setString(i++, data.getPartnerChildUid());
            call.setInt(i++, data.getPartnerChildTalent());
            call.setInt(i++, data.getPartnerChildOccupation());
            call.setString(i++, data.getPartnerChildName());
            call.setInt(i++, data.getPartnerChildSex());
            call.setInt(i++, data.getPartnerChildHeadIcon());
            reward = PropertyHelper.parsePropertyToString(data.getPartnerReward());
            if(null == reward){
                reward = "";
            }
            call.setString(i++, reward);
            call.setInt(i++, data.getChildOccupationId());
            call.setString(i++, data.getChildEarnSpeed().toString());
            call.setInt(i++, data.getPartnerChildOccupationId());
            call.setString(i++, data.getPartnerChildEarnSpeed().toString());
            call.setString(i++, data.getTotalChildEarnSpeed().toString());
            call.setInt(i++, data.getMotherId());
            call.setInt(i++, data.getPartnerMotherId());
            call.setBoolean(i++, data.isTwins());
            call.setBoolean(i++, data.isPartnerTwins());
            call.setLong(i++, data.getServerId());
            call.setLong(i++, data.getPartnerServerId());
            call.setBoolean(i++, data.isCanHoneyMoon());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(MarriageRecord data) {
        PreparedStatement call = null;
        String sql = "UPDATE t_u_marriage_record SET userNickName=?,childTalent=?,childOccupation=?,childName=?,childSex=?,childHeadIcon=?,childAdultTime=?,"
                + "publishTime=?,appointUserId=?,reward=?,marriageTime=?,partnerUserId=?,partnerNickName=?,partnerChildUid=?,partnerChildTalent=?,"
                + "partnerChildOccupation=?,partnerChildName=?,partnerChildSex=?,partnerChildHeadIcon=?,partnerReward=?,childOccupationId=?,childEarnSpeed=?,"
                + "partnerChildOccupationId=?,partnerChildEarnSpeed=?,totalChildEarnSpeed=?,motherId=?,partnerMotherId=?,isTwins=?,isPartnerTwins=?," +
                "serverId=?,partnerServerId=?,canHoneyMoon = ? where userId=? and childUid=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getUserNickName());
            call.setInt(i++, data.getChildTalent());
            call.setInt(i++, data.getChildOccupation());
            call.setString(i++, data.getChildName());
            call.setInt(i++, data.getChildSex());
            call.setInt(i++, data.getChildHeadIcon());
            call.setLong(i++, data.getChildAdultTime());
            call.setLong(i++, data.getPublishTime());
            call.setLong(i++, data.getAppointUserId());
            String reward = PropertyHelper.parsePropertyToString(data.getReward());
            if(null == reward){
                reward = "";
            }
            call.setString(i++, reward);
            call.setLong(i++, data.getMarriageTime());
            call.setLong(i++, data.getPartnerUserId());
            call.setString(i++, data.getPartnerNickName());
            call.setString(i++, data.getPartnerChildUid());
            call.setInt(i++, data.getPartnerChildTalent());
            call.setInt(i++, data.getPartnerChildOccupation());
            call.setString(i++, data.getPartnerChildName());
            call.setInt(i++, data.getPartnerChildSex());
            call.setInt(i++, data.getPartnerChildHeadIcon());
            reward = PropertyHelper.parsePropertyToString(data.getPartnerReward());
            if(null == reward){
                reward = "";
            }
            call.setString(i++, reward);
            call.setInt(i++, data.getChildOccupationId());
            call.setString(i++, data.getChildEarnSpeed().toString());
            call.setInt(i++, data.getPartnerChildOccupationId());
            call.setString(i++, data.getPartnerChildEarnSpeed().toString());
            call.setString(i++, data.getTotalChildEarnSpeed().toString());
            call.setInt(i++, data.getMotherId());
            call.setInt(i++, data.getPartnerMotherId());
            call.setBoolean(i++,data.isTwins());
            call.setBoolean(i++,data.isPartnerTwins());
            call.setLong(i++, data.getServerId());
            call.setLong(i++, data.getPartnerServerId());
            call.setBoolean(i++, data.isCanHoneyMoon());
            call.setLong(i++, data.getUserId());
            call.setString(i++, data.getChildUid());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected MarriageRecord parseData(ResultSet rs) throws SQLException {
        MarriageRecord data = new MarriageRecord();
        data.setUserId(rs.getLong("userId"));
        data.setUserNickName(rs.getString("userNickName"));
        data.setChildUid(rs.getString("childUid"));
        data.setChildTalent(rs.getInt("childTalent"));
        data.setChildName(rs.getString("childName"));
        data.setChildSex(rs.getInt("childSex"));
        data.setChildOccupation(rs.getInt("childOccupation"));
        data.setChildHeadIcon(rs.getInt("childHeadIcon"));
        data.setChildAdultTime(rs.getLong("childAdultTime"));
        data.setPublishTime(rs.getLong("publishTime"));
        data.setAppointUserId(rs.getLong("appointUserId"));
        data.setReward(PropertyHelper.parseStringToProperty(rs.getString("reward")));
        data.setMarriageTime(rs.getLong("marriageTime"));
        data.setChildOccupationId(rs.getInt("childOccupationId"));
        data.setPartnerUserId(rs.getLong("partnerUserId"));
        data.setPartnerNickName(rs.getString("partnerNickName"));
        data.setPartnerChildUid(rs.getString("partnerChildUid"));
        data.setPartnerChildTalent(rs.getInt("partnerChildTalent"));
        data.setPartnerChildName(rs.getString("partnerChildName"));
        data.setPartnerChildSex(rs.getInt("partnerChildSex"));
        data.setPartnerChildOccupation(rs.getInt("partnerChildOccupation"));
        data.setPartnerChildHeadIcon(rs.getInt("partnerChildHeadIcon"));
        data.setPartnerReward(PropertyHelper.parseStringToProperty(rs.getString("partnerReward")));
        data.setPartnerChildOccupationId(rs.getInt("partnerChildOccupationId"));
        String value = rs.getString("childEarnSpeed");
        if(!StringUtils.isNullOrEmpty(value)){
            data.setChildEarnSpeed(new BigInteger(value));
        }
        value = rs.getString("partnerChildEarnSpeed");
        if(!StringUtils.isNullOrEmpty(value)){
            data.setPartnerChildEarnSpeed(new BigInteger(value));
        }
        value = rs.getString("totalChildEarnSpeed");
        if(!StringUtils.isNullOrEmpty(value)){
            data.setTotalChildEarnSpeed(new BigInteger(value));
        }
        data.setMotherId(rs.getInt("motherId"));
        data.setPartnerMotherId(rs.getInt("partnerMotherId"));
        data.setTwins(rs.getBoolean("isTwins"));
        data.setPartnerTwins(rs.getBoolean("isPartnerTwins"));
        data.setServerId(rs.getLong("serverId"));
        data.setPartnerServerId(rs.getLong("partnerServerId"));
        data.setCanHoneyMoon(rs.getBoolean("canHoneyMoon"));
        return data;
    }

    public Map<String, MarriageRecord> getCanMarriageRecord(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<String, MarriageRecord> recordMap = new ConcurrentHashMap<>();
        String sql = "select * from t_u_marriage_record where userId=? and canHoneyMoon = ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            call.setBoolean(2,true);
            rs = call.executeQuery();
            while (rs.next()) {
                MarriageRecord data = parse(rs);
                recordMap.put(data.getChildUid(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return recordMap;
    }

    /**
     * 获取可度蜜月记录（指定职业）
     * @param userId
     * @param occupation
     * @param limit
     * @return
     */
    public Map<String, MarriageRecord> getCanMarriageRecordNew(long userId, long occupation, int limit) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<String, MarriageRecord> recordMap = new ConcurrentHashMap<>();
        String sql = "select * from t_u_marriage_record where userId=? and canHoneyMoon = ? AND (childOccupation = ? OR partnerChildOccupation = ?) ORDER BY totalChildEarnSpeed+0 DESC LIMIT ?;";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            call.setBoolean(2, true);
            call.setLong(3, occupation);
            call.setLong(4, occupation);
            call.setInt(5, limit);
            rs = call.executeQuery();
            while (rs.next()) {
                MarriageRecord data = parse(rs);
                recordMap.put(data.getChildUid(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return recordMap;
    }

    /**
     * 获取可度蜜月记录（不指定职业）
     * @param userId
     * @param limit
     * @return
     */
    public Map<String, MarriageRecord> getCanMarriageRecordNew(long userId, int limit) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<String, MarriageRecord> recordMap = new ConcurrentHashMap<>();
        String sql = "select * from t_u_marriage_record where userId=? and canHoneyMoon = ? ORDER BY totalChildEarnSpeed+0 DESC LIMIT ?;";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            call.setBoolean(2, true);
            call.setInt(3, limit);
            rs = call.executeQuery();
            while (rs.next()) {
                MarriageRecord data = parse(rs);
                recordMap.put(data.getChildUid(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return recordMap;
    }

    public long getCanMarriageRecordCount(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select count(*) as count from t_u_marriage_record where userId=? and canHoneyMoon = ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            call.setBoolean(2,true);
            rs = call.executeQuery();
            while (rs.next()) {
                return rs.getLong("count");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return 0;
    }
}
